package io.boot.modules.msg.service.impl;

import com.alibaba.fastjson.JSON;
import io.boot.modules.msg.entity.MsgInfoEntity;
import io.boot.modules.msg.service.MsgInfoService;
import io.boot.modules.sys.entity.SysUserEntity;
import io.boot.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.boot.common.utils.PageUtils;
import io.boot.common.utils.Query;

import io.boot.modules.msg.dao.MessageDao;
import io.boot.modules.msg.entity.MessageEntity;
import io.boot.modules.msg.service.MessageService;


@Service("messageService")
public class MessageServiceImpl extends ServiceImpl<MessageDao, MessageEntity> implements MessageService {

    @Autowired
    private WebSocketMsgServer webSocketMsgServer;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MsgInfoService msgInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MessageEntity> page = this.page(
                new Query<MessageEntity>().getPage(params),
                new QueryWrapper<MessageEntity>()
                .in((List<Long>) params.get("list")!=null,"create_by",(List<Long>) params.get("list"))
                .orderByAsc("status").orderByDesc("create_time")
        );

        return new PageUtils(page);
    }

    @Override
    public Date getLastDate(Long userId) {
        return baseMapper.getLastDate(userId);
    }


    public void sendMsg(Long userId){
        Date date=this.getLastDate(userId);
        SysUserEntity sysUserEntity=sysUserService.getById(userId);

        //根据时间获取应该推送的消息
        List<MsgInfoEntity> msgInfoEntityList=msgInfoService.getMsgInfoList(date,sysUserEntity.getDeptId());
        for (MsgInfoEntity msg:msgInfoEntityList) {
            SysUserEntity sender=sysUserService.getById(msg.getCreateBy());
            Map<String,Object> msgE=new HashMap<>();
            msgE.put("title",msg.getTitle());
            msgE.put("content",msg.getContent());
            Boolean flag=webSocketMsgServer.sendInfo(JSON.toJSONString(msgE),String.valueOf(userId));
            if(flag) {
                MessageEntity messageEntity = new MessageEntity();
                messageEntity.setSender(sender.getUsername());
                messageEntity.setReceiver(sysUserEntity.getUsername());
                messageEntity.setMsgInfoId(msg.getMsgInfoId());
                messageEntity.setStatus(0);
                messageEntity.setCreateBy(userId);
                messageEntity.setCreateTime(new Date());
                this.save(messageEntity);
            }
        }
    }

}
